app = @bhv
app.directive('waveChart', ->
  restrict: 'A'
  replace: false
  scope:  {color: '@'}
  controller: ($scope)->
    ###
      @waveHeight 波高（波峰和波谷的差距）
      @waveWidth 一个完整的波的宽度[0, 2π]
      @transformX, transformY  平移量 []
    ###
    @getWaveFunc = (waveHeight, waveWidth, transformX = 0, transformY = 0)->
      (x)-> (waveHeight / 2) * Math.sin( (x + transformX)* (2*Math.PI/waveWidth)) + transformY

    @setStyle = (ctx)->
      ctx.strokeStyle = ctx.fillStyle = $scope.color

  link: ($scope, element, attrs, ctrl)->
    $root = $(element)
    $convas = $("<canvas></canvas>")
    rootWidth = $root.width()
    rootHeight = $root.height()
    $convas.attr('width', rootWidth)
    $convas.attr('height', rootHeight)
    $root.append($convas)
    canvas = $root.find('canvas')[0]
    ctx = canvas.getContext("2d")
    ctrl.setStyle(ctx)

    buildWave = (width, height, transformY, transformX = 0)->
      f = ctrl.getWaveFunc(height, width, transformX, transformY)
      ctx.clearRect(0, 0, width, height)
      ctx.beginPath()
      for x in [0..width]
        ctx.lineTo(x, f(x))
      ctx.lineTo(width, height)
      ctx.lineTo(0, height)
      ctx.lineTo(0, f(0))
      ctx.fill()
      ctx.stroke()

      if transformX <= width
        transformX = transformX + 1
      else
        transformX = 0

      setTimeout(
        ()-> buildWave(width, height, height/2, transformX)
      , 50
      )

    buildWave(rootWidth, rootHeight, rootHeight/2 + 1, 0)

)